import { defineStore } from 'pinia';
import { login, register, logout, getCurrentUser, updateProfile } from '../api/auth';
import { message } from 'ant-design-vue';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    user: JSON.parse(localStorage.getItem('user') || 'null'),
    loading: false
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    userId: (state) => state.user?.id,
    username: (state) => state.user?.username,
    nickname: (state) => state.user?.nickname || state.user?.username,
    avatar: (state) => state.user?.avatar
  },
  
  actions: {
    async login(credentials) {
      this.loading = true;
      try {
        const response = await login(credentials);
        console.log('登录响应:', response); // 调试信息
        
        // auth.js已经处理了localStorage保存，这里只需要更新store状态
        if (response.success && response.data) {
          this.token = response.data.token;
          this.user = response.data.user;
          console.log('登录成功，token:', this.token); // 调试信息
          console.log('用户信息:', this.user); // 调试信息
          return response.data;
        } else {
          throw new Error('登录响应格式错误');
        }
      } catch (error) {
        console.error('登录错误详情:', error); // 调试信息
        message.error(error.message || '登录失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async register(userData) {
      this.loading = true;
      try {
        const data = await register(userData);
        return data;
      } catch (error) {
        message.error(error.message || '注册失败');
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    logout() {
      logout();
      this.token = null;
      this.user = null;
      
      // 发布登出事件，让其他store可以响应
      window.dispatchEvent(new CustomEvent('user-logout'));
    },
    
    async fetchUserProfile() {
      if (!this.token) return;
      
      this.loading = true;
      try {
        const data = await getCurrentUser();
        this.user = data;
        localStorage.setItem('user', JSON.stringify(data));
      } catch (error) {
        console.error('获取用户信息失败:', error);
      } finally {
        this.loading = false;
      }
    },
    
    async updateProfile(userData) {
      this.loading = true;
      try {
        const data = await updateProfile(userData);
        this.user = { ...this.user, ...data };
        localStorage.setItem('user', JSON.stringify(this.user));
        message.success('个人资料更新成功');
        return data;
      } catch (error) {
        message.error(error.message || '更新个人资料失败');
        throw error;
      } finally {
        this.loading = false;
      }
    }
  }
});